#ifndef __THREAD_H__
#define __THREAD_H__

#include <pthread.h>
#include <sched.h>


/**
 * A class that wraps a thread. Extend this class to create threads. The default
 * implementation uses pthreads, you must customize this to work on your platform.
 */
class SimpleThread {
public:
    SimpleThread();
    virtual ~SimpleThread();
    /**
     * Call this method to start running the thread.
     */
    bool start();
    /**
     * Call this method to wait for the thread represented by this object to terminate.
     * You are responsible for actually making the thread shutdown somehow.
     */
    bool join();
    /**
     * Return an identifier for this thread.
     */
    unsigned long id();
    /**
     * Yield the cpu to any other runnable threads.
     */
    void yield();
    /**
     * Return running state for this thread.
     */
    bool isRunning() const { return mRunning; }
    /**
     * Set the thread priority.
     * @param priority The priority value to set. You should check the range of priority values
     *        that your system supports.
     * @return True on success, false otherwise.
     */
    bool setPriority(int priority);
    /**
     * Set the name of the thread.
     * @param name The name of this thread.
     * @return True on success, false otherwise.
     */
    bool setName(const char* name);

    /**
     * @brief selfId
     * @return Return an identifier for current running thread.
     */
    static unsigned long selfId();

    void cancel();

    static void msleep(int msec);

    static void sleep(int sec);

    //! 判断当前执行流程是否在相同上下文
    bool isCommonContent();

protected:
    /**
     * @internal
     * The actual method sent to pthreads to run. This calls the overloaded run
     * method internally. The this pointer is sent across while calling pthread_create
     * so we can differentiate objects.
     * @param arg The address of the thread object that needs to be run.
     */
    static void* callback(void* arg);

    /**
     * Override this method with your actual thread startup function.
     * This function will call before run()
     */
    virtual void startup() {}
    /**
     * Override this method with your actual thread function. The idea is that since
     * you have to extend this class, you can add any necessary methods to set up the
     * state that your threads need.
     */
    virtual void run() = 0;

    /**
     * Override this method with your actual thread cleanup function.
     * This function will call after run()
     */
    virtual void cleanup() {}

private:
    pthread_t mThread;
    bool mRunning;
    bool mJoin;
    pthread_mutex_t mMutex;	
};


#endif  // __THREAD_H__
